package linearstructure.queue.circle;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-05-23 14:56
 * @ Description : 环形队列
 */
public class CircleQueue
{
    private final int maxSize;
    private int front;//队列头(指向第一个元素)
    private int rear;//队列尾(指向最后一个元素的后一个位置)
    private int[] arr;//队列数组,模拟队列

    public CircleQueue(int arrayMaxSize)
    {
        maxSize = arrayMaxSize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

    public boolean isFull()
    {
        return (rear + 1) % maxSize == front;
    }

    public boolean isEmpty()
    {
        return rear == front;
    }

    public void addQueue(int n)
    {
        if (isFull())
        {
            System.out.println("队列已满！");
            return;
        }
        arr[rear] = n;
        //将rear后移
        rear = (rear + 1) % maxSize;
    }

    public int getQueue()
    {
        if (isEmpty())
        {
            throw new RuntimeException("队列为空,不能取出数据！");
        }
        int value = arr[front];
        front = (front + 1) % maxSize;
        return value;
    }

    public void showQueue()
    {
        //遍历
        if (isEmpty())
        {
            System.out.println("队列为空,不能遍历！");
            return;
        }
        for (int i = front; i < front + size(); i++)
        {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    public int size()
    {
        return (rear + maxSize - front) % maxSize;
    }

    //显示头数据
    public int headQueue()
    {
        if (isEmpty())
        {
            System.out.println("队列为空");
            throw new RuntimeException("队列为空");
        }
        return arr[front];
    }
}
